import { showFailToast } from "vant";
import axios, {
  AxiosResponse,
  AxiosError,
  InternalAxiosRequestConfig,
} from "axios";
import { isLogin } from "@/utils/token";
const service = axios.create({
  baseURL:
    import.meta.env.VITE_APP_BASE_API + import.meta.env.VITE_APP_PUBLIC_PATH,
  withCredentials: false,
  timeout: 60000,
});

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (isLogin() && config?.headers) {
      config.headers["x-access-token"] = isLogin();
      config.headers["user-flag"] = "dd";
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;
    if (res.code != 0) {
      if (["401"].includes(res.code)) {
        showFailToast(res.msg);
        return Promise.reject(res.msg || res.message || "Error");
      } else {
        showFailToast(res.msg || res.message || "Error");
        return Promise.reject(response);
      }
    } else {
      return res;
    }
  },
  (error: AxiosError) => {
    showFailToast(error.message);
    return Promise.reject(error);
  }
);

export default service;
